package com.chen.librarysystem.controller;

import com.chen.librarysystem.context.AppContext;
import com.chen.librarysystem.entry.User;
import com.chen.librarysystem.enumenrty.LogState;
import com.chen.librarysystem.log.LibraryLog;
import com.chen.librarysystem.menu.AdminBookMenu;
import com.chen.librarysystem.menu.UserBookMenu;
import com.chen.librarysystem.service.UserService;
import com.chen.librarysystem.service.impl.UserServiceImpl;
import com.chen.librarysystem.util.PrintUtils;

import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;

public class BookController {
    private final Scanner sc = AppContext.getInstance().getScanner();
    private final UserService userService = new UserServiceImpl();

    public void register() {
        String username = PrintUtils.getInput("请输入用户名:");
        String password = PrintUtils.getInput("请输入密码:");
        String role = PrintUtils.getInput("请输入用户角色:");
        User user = new User(username, password, role);
        // 判断用户是否已注册
        if (userService.isRegistered(user.getName(), user.getPassword())) {
            System.out.println("用户已存在！请直接登录");
            LibraryLog.log(Level.WARNING, "用户已存在！请直接登录");
            return;
        }
        userService.register(user);
        System.out.println("注册成功！");

    }

    public void login() {
        String username = PrintUtils.getInput("请输入用户名:");
        String password = PrintUtils.getInput("请输入密码:");
        AppContext.getInstance().setUserName(username);
        AppContext.getInstance().setPassword(password);
        Map<LogState, User> login = userService.login(username, password);
        User user = login.get(LogState.SUCCESS);
        if (user != null) {
            System.out.println("登录成功！");
            if (user.getRole().equals("admin")) {
                new AdminBookMenu().start();
            } else if (user.getRole().equals("user")) {
                new UserBookMenu().start();
            }
        } else {
            System.out.println("您未注册，请先注册再登录！");
        }
    }
}
